'use strict'

const { Controller } = require('egg')

class LeavewordController extends Controller {
  // 新增留言
  async createLeaveword() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      content: { type: 'string', required: true, range: { max: 300 }, desc: '留言内容' },
      name: { type: 'string', range: { max: 20 }, desc: '签名' },
      img_url: { type: 'string', range: { max: 500 }, desc: '图片' },
      wall_id: { type: 'int', required: true, desc: '墙的id' },
      label_id: { type: 'int', required: true, desc: '标签id' },
      color_id: { type: 'int', required: true, desc: '颜色id' }
    })
    let { content, name, img_url, wall_id, label_id, color_id } = ctx.request.body
    if (!name) name = '匿名'
    const user_id = ctx.authUser.id
    const result = await app.model.Leaveword.create({
      content,
      name,
      img_url,
      wall_id,
      user_id,
      label_id,
      color_id
    })
    ctx.apiSuccess(result)
  }
  // 获取留言(未登录)
  async getLeaveword() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      wall_id: { type: 'int', required: true, desc: '墙的id' },
      label_id: { type: 'int', defValue: 0, desc: '标签的id' },
      order: {
        type: 'string',
        range: { in: ['time', 'like', 'comment'] },
        defValue: 'time',
        desc: '排序方式'
      },
      page: { type: 'int', desc: '页码' },
      pageSize: { type: 'int', desc: '每页条数' }
    })
    const { wall_id, label_id, order } = ctx.request.query
    const Sequelize = app.model

    // 查找全部||根据标签查找
    const where = label_id === 0 ? { wall_id } : { wall_id, label_id }
    // 排序条件
    const defaultOrder = [['id', 'DESC']]

    // 喜欢/评论数量排序
    if (order === 'like') {
      defaultOrder.unshift([Sequelize.literal('like_count'), 'DESC'])
    } else if (order === 'comment') {
      defaultOrder.unshift([Sequelize.literal('comment_count'), 'DESC'])
    }

    // 数据库查询
    let result = await ctx.page('Leaveword', where, {
      attributes: {
        include: [
          [
            Sequelize.literal(
              `(SELECT COUNT(*) FROM feedback WHERE feedback.leaveword_id = leaveword.id AND feedback.type = 1)`
            ),
            'like_count'
          ],
          [
            Sequelize.literal(
              `(SELECT COUNT(*) FROM comment WHERE comment.leaveword_id = leaveword.id)`
            ),
            'comment_count'
          ]
        ]
      },
      order: defaultOrder
    })

    // 获取用户是否喜欢
    result = JSON.parse(JSON.stringify(result))
    result.rows = result.rows.map((item) => {
      item.is_like = false
      return item
    })

    ctx.apiSuccess(result)
  }
  // 获取留言(已登录)
  async getgetLeavewordAuth() {
    const { ctx, service, app } = this
    // 参数验证
    ctx.validate({
      wall_id: { type: 'int', required: true, desc: '墙的id' },
      label_id: { type: 'int', defValue: 0, desc: '标签的id' },
      order: {
        type: 'string',
        range: { in: ['time', 'like', 'comment'] },
        defValue: 'time',
        desc: '排序方式'
      },
      page: { type: 'int', desc: '页码' },
      pageSize: { type: 'int', desc: '每页条数' }
    })
    const { wall_id, label_id, order } = ctx.request.query
    const Sequelize = app.model

    // 查找全部||根据标签查找
    const where = label_id === 0 ? { wall_id } : { wall_id, label_id }
    // 排序条件
    const defaultOrder = [['id', 'DESC']]

    // 根据喜欢/评论数量排序
    if (order === 'like') {
      defaultOrder.unshift([Sequelize.literal('like_count'), 'DESC'])
    } else if (order === 'comment') {
      defaultOrder.unshift([Sequelize.literal('comment_count'), 'DESC'])
    }

    // 数据库查询
    let result = await ctx.page('Leaveword', where, {
      attributes: {
        include: [
          [
            Sequelize.literal(
              `(SELECT COUNT(*) FROM feedback WHERE feedback.leaveword_id = leaveword.id AND feedback.type = 1)`
            ),
            'like_count'
          ],
          [
            Sequelize.literal(
              `(SELECT COUNT(*) FROM comment WHERE comment.leaveword_id = leaveword.id)`
            ),
            'comment_count'
          ]
        ]
      },
      order: defaultOrder
    })

    // 获取用户是否喜欢
    result = JSON.parse(JSON.stringify(result))
    const user_id = ctx.authUser.id // 当前用户id
    result = await service.leaveword.getListAuth(user_id, result)

    ctx.apiSuccess(result)
  }
  // 获取全部留言(admin)
  async getLeavewordAll() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      page: { type: 'int', desc: '页码' },
      pageSize: { type: 'int', desc: '每页条数' },
      id: { type: 'int', desc: '留言id' },
      content: { type: 'string', desc: '留言内容' },
      name: { type: 'string', desc: '签名' },
      wall_id: { type: 'int', desc: '墙的id' },
      label_id: { type: 'int', desc: '标签的id' }
    })
    const { content, name, id, wall_id, label_id } = ctx.request.query
    const Op = app.Sequelize.Op
    // 整理查询条件
    let where = {}
    if (content) where.content = { [Op.like]: `%${content}%` }
    if (name) where.name = { [Op.like]: `%${name}%` }
    if (id) where.id = id
    if (wall_id) where.wall_id = wall_id
    if (label_id) where.label_id = label_id

    let result = await ctx.page('Leaveword', where, {
      include: [
        { model: app.model.Wall, attributes: ['title'] },
        { model: app.model.Label, attributes: ['name'] },
        { model: app.model.Color, attributes: ['color'] },
        { model: app.model.User, attributes: ['id', 'username', 'nickname', 'avatar', 'status'] }
      ],
      attributes: {
        exclude: ['wall_id', 'label_id', 'color_id', 'user_id']
      }
    })
    result = JSON.parse(JSON.stringify(result))
    // 统计喜欢个数和评论个数
    for (let index = 0; index < result.rows.length; index++) {
      result.rows[index].like_count = await app.model.Feedback.count({
        where: { leaveword_id: result.rows[index].id, type: 1 }
      })
      result.rows[index].comment_count = await app.model.Comment.count({
        where: { leaveword_id: result.rows[index].id }
      })
    }

    ctx.apiSuccess(result)
  }
  // 删除留言
  async deleteLeaveword() {
    const { ctx, app, service } = this
    // 参数验证
    ctx.validate({
      ids: { type: 'string', required: true, desc: '留言id' }
    })
    let { ids } = ctx.request.body
    // 整理参数
    ids = ids.split(',').map((id) => parseInt(id))
    // 删除oss上的图片
    const leavewordList = await app.model.Leaveword.findAll({ where: { id: ids } })
    const fileUrls = leavewordList
      .filter((item) => item.img_url?.startsWith('http'))
      .map((item) => item.img_url)
    await service.common.deleteFiles(fileUrls)
    // 删除留言
    const result = await app.model.Leaveword.destroy({ where: { id: ids } })

    ctx.apiSuccess(result)
  }
}

module.exports = LeavewordController
